package com.itheima.mp.domain.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author：余小小
 * @date：2024/7/18
 * @notes：分页结果
 */
@Data
@ApiModel(description = "分页结果")
public class PageDTO<T> {
    @ApiModelProperty("总条数")
    private Long total;
    @ApiModelProperty("总页数")
    private Long pages;
    @ApiModelProperty("集合")
    private List<T> list;

    public static <PO, VO> PageDTO<VO> of(Page<PO> page,Class<VO> clazz) {
        PageDTO<VO> pageDTO = new PageDTO<>();
        pageDTO.setTotal(page.getTotal()); //总条数
        pageDTO.setPages(page.getPages()); //总页数
        List<PO> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            pageDTO.setList(Collections.emptyList());
            return pageDTO;
        }
        List<VO> userVOS = BeanUtil.copyToList(records, clazz);
        pageDTO.setList(userVOS);
//        4.返回
        return pageDTO;
    }
    public static <PO, VO> PageDTO<VO> of(Page<PO> page, Function<PO,VO> convertor) {
        PageDTO<VO> pageDTO = new PageDTO<>();
        pageDTO.setTotal(page.getTotal()); //总条数
        pageDTO.setPages(page.getPages()); //总页数
        List<PO> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            pageDTO.setList(Collections.emptyList());
            return pageDTO;
        }
        List<VO> collect = records.stream().map(convertor).collect(Collectors.toList());
        pageDTO.setList(collect);
//        4.返回
        return pageDTO;
    }

}
